package com.woyou.utils;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * UI相关的工具类
 * 
 * @author longtao.li
 * 
 */
public class UIUtils {

	private static final String TAG = "UIUtils";

	/**
	 * 动态改变ListView高度
	 * 
	 * @param listView
	 * @param maxHegiht 最大高度,如果是-1则不限定最大高度
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView, int maxHegiht)throws Exception {
			Log.i(TAG, "setListViewHeightBasedOnChildren");
			ListAdapter listAdapter = listView.getAdapter();
			if (listAdapter == null) {
				return;
			}
			int totalHeight = 0;
			for (int i = 0; i < listAdapter.getCount(); i++) {
				View listItem = listAdapter.getView(i, null, listView);
				listItem.measure(0, 0);
				totalHeight += listItem.getMeasuredHeight();
			}
			ViewGroup.LayoutParams params = listView.getLayoutParams();
			totalHeight = totalHeight
					+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
			if( maxHegiht != -1 && totalHeight > maxHegiht ){
				totalHeight = maxHegiht;
			}
			params.height = totalHeight;
			// ((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
			listView.setLayoutParams(params);

	}

}
